//
//  WQUserAccountModel.swift
//  WeiBo
//
//  Created by Xmen on 16/9/22.
//  Copyright © 2016年 111. All rights reserved.
//

import UIKit

class WQUserAccountModel: NSObject {

    //  单例
    static let sharedUserAccountViewModel: WQUserAccountModel = WQUserAccountModel()
    //  用户归档用户对象
    var userAccount: WQUserAccount? {
        //  获取沙盒路径
        return WQUserAccount.loadUserAccount()
    }
    
    //  判断是登录
    var isLogin: Bool {
        return accessToken != nil
    }
    
    //  判断Accesstoken是否过期
    var accessToken: String? {
        //  获取access_token
        let token = userAccount?.access_token
        //  获取过期时间对象
        let expiresDate = userAccount?.expiresDate
        //  判断Accesstoken是否过期
        
        if let t = token {
            if expiresDate?.compare(Date()) == .orderedDescending {
                return t
                
            } else {
                //  过期
                return nil
            }
        } else {
            return nil
        }
        
    }
    
    
    
    
    
    //  获取accesstoken
    func requestAccesstoken(code: String, callBack: @escaping (Bool)->()) {
        
        WQNetworkTool.sharedTool.requestAccessToken(code: code) { (response, error) in
            if error != nil {
                print("网络请求异常: \(error)")
                callBack(false)
                return
            }
            
            //  网络请求成功
            guard let dic = response as? [String: Any] else {
                print("你是不是一个正确的字典格式")
                callBack(false)
                return
            }
            
            //  字典格式没有问题
            let userAccount = WQUserAccount(dic: dic)
            print(userAccount.access_token)
            //  获取用户信息
            self.requestUserInfo(userAccount: userAccount, callBack: callBack)
            print(userAccount.access_token)
        }
        
        
    }
    
    //  获取用户信息
    private func requestUserInfo(userAccount: WQUserAccount
        , callBack: @escaping (Bool)->()) -> Void {
        
        WQNetworkTool.sharedTool.requestStatuses(accessToken: userAccount.access_token!, uid:userAccount.uid) { (response, error) in
            
            if error != nil {
                print("网络请求异常: \(error)")
                callBack(false)
                return
            }
            
            //  代码执行到此网络请求成功
            guard let dic = response as? [String: Any] else {
                print("你不是一个正确的字典")
                callBack(false)
                return
            }
            
            let name = dic["name"]
            let avatar_large = dic["avatar_large"]
            
            
            userAccount.name = name as? String
            userAccount.avatar_large = avatar_large as? String
            
            
            print(userAccount.access_token)
            
            //  登录成功
            userAccount.saveUserAccount()
            callBack(true)
            
        }
    }
}
